/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * jfMemoriaWindows.java
 *
 * Created on 22/10/2011, 20:38:11
 */
package visao;

import agent.AgentMBean;
import java.io.IOException;
import java.text.AttributedCharacterIterator.Attribute;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import mbeanserver.MBServer;
import sun.nio.ch.SocketOpts.IP;
import util.Computer;

/**
 *
 * @author alan
 */
public class jfMemoria extends javax.swing.JFrame {

    MBeanServerConnection JMXSC;
    DefaultListModel modeloDefaultListModel = new DefaultListModel();
    MBServer mbServer;
    private ObjectName windows;
    private ObjectName linux;

    public jfMemoria(MBServer mbServer) {
        try {
            initComponents();
            this.setLocationRelativeTo(this);
            JMXSC = mbServer.getMBServer();
            windows = new ObjectName("tcc:type=MACHINEWINDOWS");
            linux = new ObjectName("tcc:type=MACHINELINUX");
        } catch (Exception ex) {
        }
    }

    public void buscaComputer() {
        try {
            String ip;
            String nome;
            Set<ObjectInstance> listaObject = JMXSC.queryMBeans(new ObjectName("tcc:*"), null);
            for (ObjectInstance objectInstance : listaObject) {
                if (objectInstance.getObjectName().getKeyProperty("type").equals("MACHINEWINDOWS")) {
                    ip = objectInstance.getObjectName().getKeyProperty("ip");
                    nome = objectInstance.getObjectName().getKeyProperty("nome");
                    Computer computer = new Computer(ip, nome, "");
                    verificaMemLivreWin(computer);
                } else {
                    if (objectInstance.getObjectName().getKeyProperty("type").equals("MACHINELINUX")) {
                        ip = objectInstance.getObjectName().getKeyProperty("ip");
                        nome = objectInstance.getObjectName().getKeyProperty("nome");
                        Computer computer = new Computer(ip, nome, "");
                        verificaMemLivreLin(computer);
                    }
                }


            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Não foi possível realizar a busca. Talvez não exista computadores ligados na rede");
        }
    }

    public void verificaMemLivreWin(Computer computer) {
        try {
            Long definicao = new Long(jtfMemoriaLivre.getText());
            Long memLivre;
            MBeanServerConnection jmx = AgentMBean.makeAgent(computer.getIp());
            memLivre = (Long) jmx.getAttribute(windows, "MemoriaLivre");
            if (memLivre <= definicao) {
                modeloDefaultListModel.addElement(computer + " -- Memória livre: " + memLivre);
            }
        } catch (MBeanException ex) {
            Logger.getLogger(jfMemoria.class.getName()).log(Level.SEVERE, null, ex);
        } catch (AttributeNotFoundException ex) {
            Logger.getLogger(jfMemoria.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstanceNotFoundException ex) {
            Logger.getLogger(jfMemoria.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ReflectionException ex) {
            Logger.getLogger(jfMemoria.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(jfMemoria.class.getName()).log(Level.SEVERE, null, ex);
        }



    }

    public void verificaMemLivreLin(Computer computer) {
        try {
            Long definicao = new Long(jtfMemoriaLivre.getText());
            Long memLivre = null;
            String memoriaLivre;
            int i = 0;
            MBeanServerConnection jmx = AgentMBean.makeAgent(computer.getIp());
            memoriaLivre = (String) jmx.getAttribute(linux, "Memoria");
            for (StringTokenizer stringTokenizer = new StringTokenizer(memoriaLivre); stringTokenizer.hasMoreTokens();) {
                String token = stringTokenizer.nextToken();
                if (i == 16) {
                    memLivre = new Long(token);
                }
                i++;
            }

            if (memLivre <= definicao) {
                modeloDefaultListModel.addElement(computer + " -- Memória livre: " + memLivre);
            }
        } catch (MBeanException ex) {
            Logger.getLogger(jfMemoria.class.getName()).log(Level.SEVERE, null, ex);
        } catch (AttributeNotFoundException ex) {
            Logger.getLogger(jfMemoria.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstanceNotFoundException ex) {
            Logger.getLogger(jfMemoria.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ReflectionException ex) {
            Logger.getLogger(jfMemoria.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(jfMemoria.class.getName()).log(Level.SEVERE, null, ex);
        }



    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpDefinicaoMemoria = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jtfMemoriaLivre = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jlPC = new javax.swing.JList();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jpDefinicaoMemoria.setBorder(javax.swing.BorderFactory.createTitledBorder("Definição de memória livre (MB)"));

        jButton1.setText("Buscar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel1.setText("Quantidade em MB");

        javax.swing.GroupLayout jpDefinicaoMemoriaLayout = new javax.swing.GroupLayout(jpDefinicaoMemoria);
        jpDefinicaoMemoria.setLayout(jpDefinicaoMemoriaLayout);
        jpDefinicaoMemoriaLayout.setHorizontalGroup(
            jpDefinicaoMemoriaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpDefinicaoMemoriaLayout.createSequentialGroup()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jtfMemoriaLivre, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 141, Short.MAX_VALUE)
                .addComponent(jButton1))
        );
        jpDefinicaoMemoriaLayout.setVerticalGroup(
            jpDefinicaoMemoriaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpDefinicaoMemoriaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1)
                .addComponent(jtfMemoriaLivre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton1))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Computadores"));

        jlPC.setModel(modeloDefaultListModel);
        jScrollPane1.setViewportView(jlPC);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 451, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 393, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jpDefinicaoMemoria, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jpDefinicaoMemoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    modeloDefaultListModel.removeAllElements();
    jlPC.validate();
    try {
        if (!"".equals(jtfMemoriaLivre.getText())) {
            try {
                Long definicao = new Long(jtfMemoriaLivre.getText());
                buscaComputer();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "Informe um número em MB para a busca");
            }
        }
        Long definicao = new Long(jtfMemoriaLivre.getText());
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Informe apenas números!");
    }
}//GEN-LAST:event_jButton1ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList jlPC;
    private javax.swing.JPanel jpDefinicaoMemoria;
    private javax.swing.JTextField jtfMemoriaLivre;
    // End of variables declaration//GEN-END:variables
}
